import React, {useEffect, useState} from 'react';
import StudentList from "./components/StudentList";
import './App.css';


const App = () => {

    const [stuData, setStuData] = useState([]);

    const [loading, setLoading] = useState(false);

    const [error, setError] = useState(null);

    useEffect(() => {
        setLoading(true);
        setError(null);

        fetch('http://localhost:1337/api/students')
            .then((res) => {
                // 判断是否正常返回响应信息
                if(res.ok){
                    return res.json();
                }
                throw new Error('数据加载失败！');
            })
            .then(data => {
                // 将加载到的数据设置到state中
                setStuData(data.data);

                // 数据加载完毕设置loading为false
                setLoading(false);
            })
            .catch((e) => {
                setLoading(false);
                // 设置错误状态
                setError(e.message);
            });

    }, []);

    return (
        <div className="app">
            {(!loading && !error) && <StudentList stus={stuData}/>}
            {loading && <p>数据正在加载中...</p>}
            {<p>{error}</p>}
        </div>
    );
};

export default App;
